﻿using System;
using System.Web;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace Eneta.Portal.Profiles
{
    public class EnetaProfilePage : WebPartPage
    {
        public static UserProfileDto GetCurrentProfile()
        {
            var rep = new UserProfileRepository(SPContext.Current.Web);
            var request = HttpContext.Current.Request;

            var idString = request.QueryString["ID"];
            if (string.IsNullOrEmpty(idString))
            {
                idString = request.QueryString["profileID"];
            }

            if(!string.IsNullOrEmpty(idString))
            {
                int id;
                if (!int.TryParse(idString, out id))
                    return null;

                return rep.GetUserProfileById(id);
            }

            var name = request.QueryString["name"];
            if(!string.IsNullOrEmpty(name))
            {
                return rep.GetUserProfileByProfileName(name);
            }
            return null;            
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var query = string.Empty;
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                query += "&profileID=" + Request.QueryString["ID"];
            if (!string.IsNullOrEmpty(Request.QueryString["msg"]))
                query += "&msg=" + Request.QueryString["msg"];

            if (query.Length > 0)
                query = "?" + query.Substring(1);


            Response.Redirect("/Lehed/profile.aspx" + query);
            Response.End();
        }
    }
}
